﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Threading;
using WpfWindowRecorder;

namespace WpfWindowRecorder
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindowRecorder? _recorder;
        private bool _isRecording = false;

        public MainWindow()
        {
            InitializeComponent();
            CompositionTarget.Rendering += OnRendering;
            this.PreviewKeyDown += MainWindow_PreviewKeyDown;
        }

        private void OnRendering(object? sender, EventArgs e)
        {
            TimeTextBlock.Text = DateTime.Now.ToString("HH:mm:ss.fff");
        }

        private async void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.R && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                e.Handled = true;
                if (!_isRecording)
                {
                    _recorder = new MainWindowRecorder();
                    _isRecording = true;
                    await _recorder.StartRecordingAsync(this);
                }
                else
                {
                    _isRecording = false;
                    if (_recorder != null)
                    {
                        string? savedPath = await _recorder.StopAndSaveRecordingAsync();
                        if (!string.IsNullOrEmpty(savedPath))
                        {
                            MessageBox.Show($"录制已保存到: {savedPath}", "录制完成", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        _recorder = null;
                    }
                }
            }
        }
    }
}